<?php
namespace App\Libs;

use GatewayClient\GatewayProtocol;
use \GatewayWorker\Lib\Gateway;
use \GatewayWorker\Lib\Db;
use \GatewayWorker\Lib\DbConnection;
use \Workerman\Lib\Timer;

class Games {

    protected $Game;

    public function __construct()
    {
        $this->Game = \jsonRpcClient::instance('Game');
    }
    #region 游戏开始

    public function gameMessage($client_id, $paras){
        //组装预备要访问的函数(过程)名
        $func = 'cmd_'.$paras['cmd'];

        if (method_exists($this, $func))
        {
            $this->$func($client_id, $paras);
        }else{
            Gateway::sendToCurrentClient(json_encode(array(
                'state' => 404,
                'msgid' => 301,
            )));
            //不自动断开，由客户端自动断开
            //Gateway::closeClient($client_id);
        }
    }
    #endregion
    #region 关闭当前链接
    public function cmd_close($client_id,$paras)
    {
        Gateway::sendToCurrentClient(json_encode(array(
            'state' => 200,
            'cmd' => 'close',
        )));
        Gateway::closeCurrentClient();
    }
    #endregion
    #region 游戏对应参数的执行过程
    //拉取游戏规则介绍
    public function cmd_gamerule($client_id, $paras)
    {
        $data = $this->Game->gameRule($paras);
        $result = $data['data'];
        Gateway::sendToCurrentClient(json_encode($result));
    }
    //列出红包游戏
    public function cmd_gamelist($client_id, $paras){
        $data = $this->Game->GameHomeData();
        $result = $data['data'];
        $result['state']= 200;
        $result['cmd'] = $paras['cmd'];
        Gateway::sendToCurrentClient(json_encode($result));

        if(array_key_exists('isclose',$paras) && $paras['isclose']) {
            Gateway::closeClient($client_id);
        }
    }
    # 重新拉取数据
    public function cmd_reloadgamedata($client_id, $paras)
    {
        $gameid = isset($paras['gameid']) ? intval($paras['gameid']) : 0;
        $rid = isset($paras['rid']) ? intval($paras['rid']) : 0;
        $result = array('state' => 404, 'cmd' => $paras['cmd'], 'msgid' => 404);
        if($gameid > 0) {
            $data = $this->Game->getGrabingRedpacket($gameid,$rid);
            //$data = $data['data'];
            if (isset($data['state']) && $data['state'] == 200) {
                $result['state'] = 200;
                unset($result['msgid']);
                $result['datas'] = $data['data'];
            }
        }
        Gateway::sendToCurrentClient(json_encode($result));
    }
    //加入游戏
    public function cmd_joingame($client_id, $paras)
    {
        global $utility;

        $gameData = $this->Game->joinToGameForIdData($paras);
        $gameData = $gameData['data'];
        $result['state'] = 404;
        $result['cmd'] = $paras['cmd'];
        if($gameData['state']==200){
            $result['state'] = 200;
            //加入到游戏的房间
            $_SESSION['room_id'] = $paras['room_id'];//房间号默认
            $_SESSION['token'] = $gameData['user']['token'];//用户名
            $_SESSION['useronline'] = true;//首页在线标志
            $_SESSION['avatar'] = $gameData['user']['avatar']; //头像
            $_SESSION['uid'] = $gameData['user']['uid'];
            $_SESSION['uno'] = $gameData['user']['uno'];
            $_SESSION['nickname'] = $gameData['user']['nickname'];
            $_SESSION['usertype'] = $gameData['user']['usertype'];
            //找出对应的红包游戏（正在进行的游戏红包列表）
            //加到组
            Gateway::joinGroup($client_id, $gameData['game_room_en_name']);
            //绑定用户的ID
            Gateway::bindUid($client_id,$gameData['user']['uno']);
            //如果系统重新连接后有期数提供
            if(!empty($gameData['red_issue'])){
                //加到这个期数组
                Gateway::joinGroup($client_id,$gameData['red_issue']);
                $result['red_issue'] = $gameData['red_issue'];
                $_SESSION['issue'] = $gameData['red_issue'];
            }
            //当前用户的余额
            $result['usercoin'] = $gameData['user']['usercoin'];
            //取游戏参数
            $gameinfo = $gameData['gameinfo'];
            $result['minbetcoin'] = $gameinfo['minbetcoin']; //最小投注
            $result['maxbetcoin'] = $gameinfo['maxbetcoin']; //最大投注
            $result['func'] = $gameinfo['func']; //算法后置函数
            $result['gameid'] = $gameinfo['id'];
            $result['maxodds'] = $gameinfo['maxodds']; //最大赔率的倍数
            $result['custombetscoin'] = $gameinfo['custombetscoin']; //是否可以自定义投注金额
            //人数配置
            $result['needuser'] = explode(',',$gameinfo['manymen']);
            //默认需要人数
            $result['defaultneed'] = $result['needuser'][0];
            //下注配置
            //$result['bets'] = $this->db->column("SELECT `bets` FROM `rp_redpacket_games` WHERE `id`={$game_id}");
            $betsCoin = explode(',',$gameinfo['betscoinlist']);
            switch ( $paras['rid'] ){
                case '1':
                    foreach ( $betsCoin as $k=>$item ){
                        if( $item >= 200 ){
                            unset($betsCoin[$k]);
                        }
                    }
                    $result['minbetcoin'] = 1;
                    $result['maxbetcoin'] = 200; //最大投注
                    break;
                case '2':
                    foreach ( $betsCoin as $k=>$item ){
                        if( $item >= 2000 || $item < 200 ){
                            unset($betsCoin[$k]);
                        }
                    }
                    $result['minbetcoin'] = 200;
                    $result['maxbetcoin'] = 2000; //最大投注
                    break;
                case '3':
                    foreach ( $betsCoin as $k=>$item ){
                        if( $item < 2000 ){
                            unset($betsCoin[$k]);
                        }
                    }
                    $result['minbetcoin'] = 2000;
                    break;
                default:

                    break;
            }
            sort($betsCoin);
            $result['bets'] = $betsCoin;
            $result['defaultbet'] = $gameinfo['minbetcoin'];
            //找出没有完成的红包
            $result['datas'] = $gameData['grabing'];
            //$result['datas'] = $this->db->query("SELECT b.`id`,b.`issue`,b.`nickname`,b.`need`,b.`cur`,b.`coin`,b.`begintimes`,b.`overtime`,IF(u.`avatar`,u.`avatar`,'no') AS avatar FROM `rp_bets` b,`rp_users` u WHERE b.`uid`=u.`id` AND b.`state`=0 AND b.`need`>b.`cur` AND b.`gameid`={$game_id}");
        }else{
            $result['state'] = $gameData['state'];
            $result['msgid'] = $gameData['msgid'];
        }
        Gateway::sendToCurrentClient(json_encode($result));
        //Gateway::closeClient($client_id);
    }
    //发红包
    public function cmd_sendred($client_id, $paras){
        global $utility;
        $data = $this->Game->sendGameEnvelopes($paras);
        $data = $data['data'];
        if(isset($data['state']) && $data['state']==200)
        {
            //print_r($data);
            //离开当前的组，自己将不会收到newred命令的推送信息
            Gateway::leaveGroup($client_id, $data['groupname']);
            $beforResult = array(
                'state' => 200,
                'cmd' => 'newred',
                'gameid' => $data['gameid'],
                'datas' => $data['datas'],
            );
            Gateway::sendToGroup($data['groupname'],json_encode($beforResult));
            //离开当前的Group，加入到自己发的红包的Group
            //抢红包的组id用用户的i来加入，然后绑定客户编号
            Gateway::joinGroup($client_id, $data['datas']['issue']);

            //绑定用户的ID
            Gateway::bindUid($client_id, $data['user']['uno']);
            //推送给自己
            $result = array(
                'state' => 200,
                'cmd' => 'sendred',
                'gameid' => $data['gameid'],
                'datas' => $data['datas'],
            );
            Gateway::sendToCurrentClient(json_encode($result));
        }else{
            $result['cmd'] = $paras['cmd'];
            $result['state'] = (isset($data['state']) ? $data['state'] : 404);
            $result['msgid'] = (isset($data['msgid']) ? $data['msgid'] : 404);
            Gateway::sendToCurrentClient(json_encode($result));
        }
    }
    //抢红包
    public function cmd_grab($client_id, $paras)
    {
        global $utility;

        $data = $this->Game->grabGameEnvelopes($paras);

        $data = $data['data'];

        if(!isset($data['state'])){
            return array(
                'cmd' => 'grab',
                'state' => 404,
                'msgid' => 404,
                );
        }
        if($data['state']==200)
        {
            # 通知玩法房间更新当期红包更新数据人数
            if(isset($data['updatered'])){
                $data['updatered']['state'] = 200;
                Gateway::sendToGroup($data['groupname'], json_encode($data['updatered']));
            }
            # 通知当前期数房间有新玩家加入抢包
            if(isset($data['newsjoingrab'])){
                Gateway::joinGroup($client_id, $data['reddata']['issue']);
                Gateway::sendToGroup($data['reddata']['issue'], json_encode($data['newsjoingrab']));
            }

            $data['datas'] = $data['reddata'];

            unset($data['reddata']);
            unset($data['updatered']);
            unset($data['newsjoingrab']);
            //unset($data['room_name']);
            $settlement = (isset($data['settlement']) ? $data['settlement'] : false);
            unset($data['settlement']);
            # 通知当前玩家打开抢包页面，列出抢包用户
            Gateway::sendToCurrentClient(json_encode($data));
            # 通知小组玩家结算
            if($settlement && isset($settlement['issue']))
            {
                Gateway::sendToGroup($settlement['issue'], json_encode($settlement));
            }
            return;
        }else{
            $result = array(
                'state' => $data['state'],
                'cmd' => 'grab',
                'msgid' => $data['msgid'],
            );
            return Gateway::sendToCurrentClient(json_encode($result));
        }
    }
    //红包超时没有抢完的处理，超时即是游戏结束
    //统一由game_over_来处理
    public function cmd_game_time_out($client_id, $paras)
    {
        $data = $this->Game->timeOutRedEnveloes($paras);
        $result = $data['data'];
        //print_r($result['settlement']);
        if(count($result)>0) {
            if (isset($result) && isset($result['state']) && $result['state'] == 200) {
                if (isset($result['timeoutdata'])) {
                    # 通知超时
                    Gateway::sendToGroup($result['timeoutdata']['issue'], json_encode($result['timeoutdata']));
                }
                if (isset($result['delred'])) {
                    # 通知页面删除红包数据
                    Gateway::sendToGroup($result['room_name'], json_encode($result['delred']));
                }
                return;
            } else {
                return Gateway::sendToCurrentClient(json_encode($result));
            }
        }
    }
    #endregion

    #获取房间功能
    public function cmd_joinrooms($client_id,$paras)
    {
        //加入房间直接加入房间组（通过mvc获取）
        Gateway::joinGroup($client_id, 'room_'.$paras['game_id']);
        $data = ['state'=>200,'cmd'=>'joinroom','msg'=>'success'];
        Gateway::sendToClient($client_id,json_encode($data));
    }

    #正在进行中的房间
    public function cmd_roomsGameList($client_id,$paras)
    {
        $data = $this->Game->roomsGameList($paras);
        if($data['state']==200){
            $result = $data['data'];
            Gateway::joinGroup($client_id, 'room_'.$paras['gameid']);
            Gateway::sendToClient($client_id,json_encode($result));
        }else{
            $result['cmd'] = $paras['cmd'];
            $result['state'] = (isset($data['state']) ? $data['state'] : 404);
            $result['msgid'] = (isset($data['msgid']) ? $data['msgid'] : 404);
            Gateway::sendToClient($client_id,json_encode($result));
        }
    }

    #进入自定义房间
    public function cmd_roomcheckpass($client_id,$paras)
    {
        $data = $this->Game->roomcheckpass($paras);
        $data = $data['data'];
        if ( Gateway::isOnline($client_id) )
        {
            Gateway::sendToClient($client_id,json_encode($data));
        }
    }
}